<?php
session_start();
if (!isset($_SESSION['username'])) {
    echo json_encode(["code" => 401, "error" => "未授权访问"], JSON_UNESCAPED_UNICODE);
    exit();
}

include 'config.php'; // 确保数据库连接已正确初始化

// 验证参数
if (!isset($_GET['orderlist']) || empty($_GET['orderlist'])) {
    echo json_encode(["code" => 400, "error" => "参数错误"], JSON_UNESCAPED_UNICODE);
    exit();
}

// 分割订单列表并过滤空值
$orderlist = explode(',', urldecode($_GET['orderlist']));
$orderlist = array_filter(array_map('trim', $orderlist));

if (empty($orderlist)) {
    echo json_encode(["code" => 400, "error" => "订单列表为空"], JSON_UNESCAPED_UNICODE);
    exit();
}

// 构建预处理 SQL
$placeholders = implode(',', array_fill(0, count($orderlist), '?'));
$sql = "DELETE FROM orders WHERE out_trade_no IN ($placeholders)";
$stmt = $conn->prepare($sql);

if (!$stmt) {
    echo json_encode(["code" => 500, "error" => "数据库错误: " . $conn->error], JSON_UNESCAPED_UNICODE);
    exit();
}

// 动态绑定参数
$types = str_repeat('s', count($orderlist));
$stmt->bind_param($types, ...$orderlist);

if ($stmt->execute()) {
    $affectedRows = $stmt->affected_rows;
    if ($affectedRows > 0) {
        echo json_encode(["code" => 200, "msg" => "成功删除 {$affectedRows} 条记录"], JSON_UNESCAPED_UNICODE);
    } else {
        echo json_encode(["code" => 404, "error" => "未找到匹配的订单"], JSON_UNESCAPED_UNICODE);
    }
} else {
    echo json_encode(["code" => 500, "error" => "执行失败: " . $stmt->error], JSON_UNESCAPED_UNICODE);
}

$stmt->close();
$conn->close();
?>
